package com.fuxian.action;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller
@Scope("prototype")
public class fileUpload extends HttpServlet {

	private String filePath = "picture";// 文件存放路径
	private String tempPath = "temp";// 临时文件目录
	/**
	 * 
	 */
	private static final long serialVersionUID = -7888198598835071504L;
	private File img;

	public File getImg() {
		return img;
	}

	public void setImg(File img) {
		this.img = img;
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			System.out.println("fileUpload");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(2 * 1024);
			System.out.println("tempPath:"+tempPath);
			factory.setRepository(new File(tempPath));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(2 * 1024 * 1024);
			List fileItems=upload.parseRequest(request);
			System.out.println("fileItemSize:"+fileItems.size());
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					processFormField(item);
				} else {
					processUploadFile(item);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 处理表单内容
	private void processFormField(FileItem item) throws Exception {
		String name = item.getFieldName();
		String value = item.getString();
		System.out.println(name + " : " + value + "\r\n");
	}

	// 处理上传的文件
	private void processUploadFile(FileItem item) throws Exception {
		// 此时的文件名包含了完整的路径，得注意加工一下
		String filename = item.getName();
		System.out.println("完整的文件名：" + filename);
		int index = filename.lastIndexOf("\\");
		filename = filename.substring(index + 1, filename.length());

		long fileSize = item.getSize();

		if ("".equals(filename) && fileSize == 0) {
			System.out.println("文件名为空 ...");
			return;
		}
		
		File uploadFile = new File(filePath+File.separator+filename);
		item.write(uploadFile);
		System.out.println(filename + " 文件保存完毕 ...");
		System.out.println("文件大小为 ：" + fileSize + "\r\n");
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	 // 初始化  
    
	public void init(ServletConfig config) throws ServletException  
    {  
        super.init(config);  
        // 从配置文件中获得初始化参数  
//       filePath = config.getInitParameter("filepath");  
//       tempPath = config.getInitParameter("temppath");  
 
//       filePath = "filepath";  
//       tempPath ="temppath";  
        
        
        
        ServletContext context = getServletContext();  
 
        filePath = context.getRealPath(filePath);  
        tempPath = context.getRealPath(tempPath);  
        System.out.println(filePath);
        System.out.println(tempPath);
        System.out.println("文件存放目录、临时文件目录准备完毕 ...");  
    }  

}
